<?php
namespace App\Lib\Upload;

class Base
{
    public $resquest;
    public $file;
    public $type;
    public $upload_type = '';
    public $base_dir = '/home/tangchao/php/easyswoole/WebRoot';
    public $formatLimit;
    public $sizeLimit;
    public $format;
    public $filename;


    public function __construct($resquest, $type = null)
    {
        $this->resquest = $resquest;
        if (!$type){
            $files = $this->resquest->getUploadedFiles();
            $files_keys = array_keys($files);
            $this->type = $files_keys[0];
        }else{
            $this->type = $type;
        }
    }

    public function upload()
    {
        if ($this->type != $this->upload_type){
            throw new \Exception("上传文件类型错误");
        }
        $this->file = $this->resquest->getUploadedFile($this->type);
        $this->filename = $this->file->getClientFilename();
        //check
        if (!$this->check()){
            return false;
        }
        $relative_dir = DIRECTORY_SEPARATOR.$this->type.DIRECTORY_SEPARATOR.date('Y').DIRECTORY_SEPARATOR.date('m').DIRECTORY_SEPARATOR.date('d').DIRECTORY_SEPARATOR;
        $absolute_dir = $this->base_dir.$relative_dir;
        if (!is_dir($absolute_dir)){
            if (!mkdir ($absolute_dir,0777,true)){
                return false;
            }
        }
        $relative_file = $relative_dir.uniqid($this->type).'.'.$this->format;
        $absolute_file = $this->base_dir.$relative_file;
        if($this->file->moveTo($absolute_file)){
            return $relative_file;
        }else{
            return false;
        }

    }

    //文件上传前的检查
    public function check()
    {
        if ($this->checkSize() && $this->checkFormat()){
            return true;
        }else{
            return false;
        }
    }

    //检查大小
    public function checkSize()
    {
        if (empty($this->file->getSize())){
            throw new \Exception("上传文件获取失败");
        }
        if (!empty($this->sizeLimit) && $this->file->getSize() > $this->sizeLimit){
            throw new \Exception("上传文件太大了");
        }
        return true;
    }

    //检查格式
    public function checkFormat()
    {
        $temp_arr = explode('.',$this->filename);
        $format = end($temp_arr);
        if (!empty($this->formatLimit) && !in_array($format,$this->formatLimit)){
            throw new \Exception("上传文件格式不支持");
        }
        $this->format = $format;
        return true;
    }

}